import { App, Plugin, PluginSettingTab, Setting, Notice } from 'obsidian';
import { PdfExportServer } from './server';

interface PdfExportPluginSettings {
    serverPort: number;
}

const DEFAULT_SETTINGS: PdfExportPluginSettings = {
    serverPort: 80
}

export default class PdfExportPlugin extends Plugin {
    settings: PdfExportPluginSettings;
    public server: PdfExportServer | null = null;

    async onload() {
        await this.loadSettings();

        // 添加设置选项卡
        this.addSettingTab(new PdfExportSettingTab(this.app, this));

        // 添加命令
        this.addCommand({
            id: 'start-pdf-server',
            name: 'Start PDF Export Server',
            callback: async () => {
                await this.startServer();
            }
        });

        this.addCommand({
            id: 'stop-pdf-server',
            name: 'Stop PDF Export Server',
            callback: async () => {
                await this.stopServer();
            }
        });

    }

    onunload() {
        this.stopServer();
    }

    async loadSettings() {
        this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
    }

    async saveSettings() {
        await this.saveData(this.settings);
    }

    public async startServer() {
        if (this.server) {
            console.log('Server already running');
            new Notice('PDF服务已在运行');
            return;
        }

        try {
            this.server = new PdfExportServer(this.settings.serverPort, this);
            await this.server.start();
            new Notice(`PDF导出服务已在端口 ${this.settings.serverPort} 上启动`);
            console.log(`PDF Export Server started on port ${this.settings.serverPort}`);
        } catch (error) {
            console.error('Failed to start server:', error);
            new Notice('启动PDF服务失败: ' + error.message);
        }
    }

    public async stopServer() {
        if (!this.server) {
            console.log('Server not running');
            new Notice('PDF服务未在运行');
            return;
        }

        try {
            await this.server.stop();
            this.server = null;
            new Notice('PDF导出服务已停止');
            console.log('PDF Export Server stopped');
        } catch (error) {
            console.error('Failed to stop server:', error);
            new Notice('停止PDF服务失败: ' + error.message);
        }
    }
}

class PdfExportSettingTab extends PluginSettingTab {
    plugin: PdfExportPlugin;

    constructor(app: App, plugin: PdfExportPlugin) {
        super(app, plugin);
        this.plugin = plugin;
    }

    display(): void {
        const {containerEl} = this;

        containerEl.empty();

        containerEl.createEl('h2', {text: 'PDF Export Server 设置'});

        new Setting(containerEl)
            .setName('服务器端口')
            .setDesc('PDF导出服务的端口号')
            .addText(text => text
                .setPlaceholder('8080')
                .setValue(this.plugin.settings.serverPort.toString())
                .onChange(async (value) => {
                    const port = parseInt(value);
                    if (!isNaN(port) && port > 0 && port < 65536) {
                        this.plugin.settings.serverPort = port;
                        await this.plugin.saveSettings();
                    }
                }));

        new Setting(containerEl)
            .setName('启动/停止服务')
            .setDesc('控制PDF导出服务的运行状态')
            .addButton(button => button
                .setButtonText('启动服务')
                .onClick(async () => {
                    await this.plugin.startServer();
                    this.display();
                }))
            .addButton(button => button
                .setButtonText('停止服务')
                .onClick(async () => {
                    await this.plugin.stopServer();
                    this.display();
                }));
    }
}
